/**
 * Created by fly on 2017/4/12.
 */

/**
 * 连接池
 * 采用模块generic-pool
 */
var connMess = require('./config');
var genericPool = require('generic-pool');
var mysql = require('mysql');

/**
 * Step 1 - Create pool using a factory object
 */
const factory = {
    create: function(){
        return new Promise(function(resolve, reject){
            var client = mysql.createConnection(connMess.potions);
            resolve(client)
        })
    },
    destroy: function(client){
        return new Promise(function(resolve){
            resolve()
        })
    }
}

var opts = {
    max: 10, // maximum size of the pool
    min: 2 // minimum size of the pool
}

var myPool = genericPool.createPool(factory, opts);

/**
 * Step 2 - Use pool in your code to acquire/release resources
 */
const resourcePromise = myPool.acquire();
exports.query = function (sql, values, callback) {
    // acquire connection - Promise is resolved
    // once a resource becomes available
    resourcePromise.then(function(client) {
        client.query(sql, values, function(err,result) {
            // return object back to pool
            if(err){
                console.log(err);
                callback(err);
            }
            callback(result);
            myPool.release(client);
        });
    }).catch(function(err){
            // handle error - this is generally a timeout or maxWaitingClients
            // error
        });

    /**
     * Step 3 - Drain pool during shutdown (optional)
     */
// Only call this once in your application -- at the point you want
// to shutdown and stop using this pool.
    myPool.drain().then(function() {
        myPool.clear();
    });
}
